<template>
	<view class="content">
		<!-- #ifdef H5 -->
		<view class="mask-confirm" v-if="showMask">
			<view class="btn" @tap="startKnock">
				开始加功德
			</view>
		</view>
		<!-- #endif -->
		<view class="" style="position: relative;z-index: 5;">
			<!-- #ifndef MP-WEIXIN -->
			<!-- #ifdef APP-PLUS -->
			<view class="" :style="{height:getAppData.statusBarHeight+'px'}"></view>
			<!-- #endif -->
			<view class="topSetting">
				<view class="left">
					<text>功德：</text><text>{{countToThousands}}</text>
				</view>
				<view class="right">
					<view class="zeroBtn" @click="toZero">
						清零
					</view>
					<view class="setting" @click="toSetting">
						设置
					</view>
				</view>
			</view>
			<!-- #endif -->
			<!-- #ifdef MP-WEIXIN -->
			<text style="padding-top: 120rpx;display: block;">{{countToThousands}}</text>
			<cover-view>
				<cover-view :style="{height:(getAppData.customTop)+'px'}"></cover-view>
				<cover-view class="topSetting" :style="{'width':( getAppData.customLeft )+'px'}">
					<cover-view class="left">
						<cover-view>功德：</cover-view>
						<cover-view class="gongDeCount">{{countToThousands}}<cover-view style="display: inline-block; width: 2rpx;line-height: 1;border: 1rpx solid #fff;"></cover-view></cover-view>
					</cover-view>
					<cover-view class="right">
						<cover-view class="zeroBtn" @click="toZero">
							<cover-view>清零</cover-view>
						</cover-view>
						<cover-view class="setting" @click="toSetting">
							<cover-view>设置</cover-view>
						</cover-view>
					</cover-view>
				</cover-view>
			</cover-view>
			<!-- #endif -->
		</view>

		<!-- <view :class="['iconBox'] " id="iconBox" @touchstart="tap" ref="iconBox"> -->
		<!-- 创建多图层 -->
		<!-- <template v-for="(item,index) in plusArr" >
					<CanvasDom v-if="item[1]" :ref="'CanvasDom'+item[0]" @transparent="canvasDestory" :num="item[0]" :key="index" style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;"></CanvasDom>
				</template> -->
		<!-- </view> -->
		<view class="" style="position: absolute;top: 0;left: 0;width: 100%;height: 100%;z-index: 2;">
			<CanvasDom v-if="renderCanvasDom" ref="CanvasDom" @transparent="canvasDestory" @touchStart="touchStart"
				:canvasInfo="canvasInfo" :countPlusFlag="countPlusFlag" :renderArr="plusArr" :plusCount="plusCount" :addType="addType" :title="title">
			</CanvasDom>
		</view>

	</view>
</template>
<script>
	let timer = null;
	let audio = null;
	const globalData = getApp().globalData;
	import {
		toThousands,
		chinaFormat
	} from "../../utils/index.js"
	import CanvasDom from "@/pages/index/components/canvas_dom.vue";
	export default {
		components: {
			CanvasDom
		},
		data() {
			return {
				cache: {},
				audio: null,
				voiceBlob: {
					A: "",
					B: "",
					C: "",
					D: "",
				},
				addType:'plus',
				title:"功德",
				plusCount:1,
				defaultCount:0,
				count: 0,
				countPlusFlag: false,
				plusArr: [],
				voiceArr: [],
				duration: 800,
				audioName: null,
				timer: null,
				loadSrc: false,
				showMask: true,
				canvasInfo: {},
				renderCanvasDom: false,
				voiceObject: {},
				hasAddEvent: [],
				onPlay: false,
				onEnded: false,
				stopFlag: false,
				playSuccess: true, //播放成功
				onCanplay: false, //可以播放
			}
		},
		computed: {
			countToThousands() {
				return toThousands(this.count)
			},
			getAppData() {
				return getApp().globalData
			}
		},
		onLoad() {},
		onShow() {
			uni.getStorage({
				key:"title",
				success:(res)=> {
					this.title = res.data
				},
				fail(err) {
					this.title = "功德"
				}
			})
			uni.getStorage({
				key:"defaultNum",
				success:(res)=> {
					this.defaultCount = res.data
				},
				fail(err) {
					this.defaultCount = 0
				}
			})
			uni.getStorage({
				key:"num",
				success:(res)=> {
					this.plusCount = res.data
				},
				fail(err) {
					this.plusCount = 1
				}
			})
			uni.getStorage({
				key:"addType",
				success:(res)=> {
					this.addType = res.data
				},
				fail(err) {
					this.addType = "plus"
				}
			})
			if (this.audio) {
				this.audio.stop ? this.audio.stop() : ""
				this.audio.destroy ? this.audio.destroy() : ""
				this.hasAddEvent = []
				this.audio = null
			}
			this.audio = uni.createInnerAudioContext();
			this.onEnded = false
			// #ifdef MP-WEIXIN
			this.audio = wx.createInnerAudioContext({
				useWebAudioImplement: true,
				obeyMuteSwitch:false
			});
			// #endif
			// #ifdef H5
			this.audio = new Audio()
			// #endif
			this.audioName = uni.getStorageSync("audioName");
			// #ifdef H5
			if(!this.voiceBlob.A){
				uni.showLoading({
					mask: true
				})
				Promise.all([
					this.getBlob("A").then((data) => ({status: "ok",data,name: "A"}), (err) => ({status: "not ok",data: false})),
					this.getBlob("B").then((data) => ({status: "ok",data,name: "B"}), (err) => ({status: "not ok",data: false})),
					this.getBlob("C").then((data) => ({status: "ok",data,name: "C"}), (err) => ({status: "not ok",data: false})),
					this.getBlob("D").then((data) => ({status: "ok",data,name: "D"}), (err) => ({status: "not ok",data: false}))
				]).then((res) => {
					res.forEach((item) => {
						this.voiceBlob[item.name] = item.data
					})
					uni.hideLoading()
					this.audio.src = this.voiceBlob[this.audioName];
				})
			}else{
				if(!this.audio.src){
					this.audio.src = this.voiceBlob[this.audioName];
				}
			}
			
			// #endif
			if (this.audioName) {
				// #ifndef H5
				this.audio.src = `/static/sounds/muyu_${this.audioName}.mp3`;
				// #endif
			} else {
				this.audioName = "A"
				// 默认木鱼声音为A
				uni.setStorage({
					key: "audioName",
					data: "A"
				})
				// #ifndef H5
				this.audio.src = `/static/sounds/muyu_${this.audioName}.mp3`;
				// #endif
			}
			// #ifdef MP-WEIXIN || APP-PLUS
			if (!this.hasAddEvent.includes("onEnded")) {
				this.hasAddEvent.push("onEnded")
				this.audio.onEnded(() => {
					this.onEndedFun()
				})
			}
			// #endif
			// #ifdef H5
			// if (!this.hasAddEvent.includes("onError")) {
			// 	this.hasAddEvent.push("onError")
			// 	this.audio.onError(() => {
			// 		console.log("error");
			// 	})
			// }
			// if (!this.hasAddEvent.includes("onPlay")) {
			// 	this.hasAddEvent.push("onPlay")
			// 	this.audio.onPlay(() => {
			// 		this.onPlay = true;
			// 		console.log("onPlay");
			// 	})
			// }
			// if (!this.hasAddEvent.includes("onStop")) {
			// 	this.hasAddEvent.push("onStop")
			// 	this.audio.onStop(() => {
			// 		if (this.onPlay) {
			// 			this.audio.play();
			// 		}
			// 	})
			// }
			// #endif
		},
		methods: {
			getBlob(name) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: `/static/sounds/muyu_${name}.mp3`,
						method: "GET",
						responseType: "arraybuffer",
						success: (res) => {
							const blob = new Blob([res.data],{ type: res.header['content-type'] })
							let blobUrl = URL.createObjectURL(blob)
							resolve(blobUrl)
							// URL.revokeObjectURL(blobUrl)
						},
						fail: (err) => {
							reject(err)
						}
					})
				})

			},
			onEndedFun() {
				// #ifdef APP-PLUS
				this.audio.offEnded ? this.audio.offEnded() : ""
				this.audio.destroy ? this.audio.destroy() : ""
				this.hasAddEvent = this.hasAddEvent.filter((item) => item !== "onEnded")
				this.audio = null
				this.onEnded = true;
				// #endif
				this.onPlay = false
			},
			canvasDestory() {
				this.plusArr = [];
			},
			startKnock() {
				this.showMask = false;
			},
			touchStart({
				x,
				y
			}) {
				this.tap(x, y)
			},
			tap(x, y) {
				this.countPlus(x, y);
				if (this.timer) {
					clearTimeout(this.timer);
					this.timer = null;
				}
				this.timer = setTimeout(() => {
					this.countPlusEnd();
				}, 30)
			},
			// 初始化audio
			initAudio() {
				// #ifdef H5
				this.audioPlay()
				// #endif
				// #ifdef MP-WEIXIN
				if (this.onPlay) {
					// this.audio.stop()
					// this.audio.pause()
					this.audio.seek(0)
					return
				}
				this.audio.play()
				this.onPlay = true
				// #endif
				// #ifdef APP-PLUS
				if (this.onEnded) {
					this.audio = uni.createInnerAudioContext();
					this.onEnded = false
					if (!this.hasAddEvent.includes("onEnded")) {
						this.hasAddEvent.push("onEnded")
						this.audio.onEnded(() => {
							this.onEndedFun()
						})
					}
					this.audio.src = `/static/sounds/muyu_${this.audioName}.mp3`;
				}
				if (this.onPlay) {
					this.audio.seek(0);
					return
				}
				this.audio.play();
				this.onPlay = true
				// #endif
			},
			audioPlay() {
				// if (this.onPlay) {
				// 	this.audio.stop()
				// 	return
				// }
				// console.log(this.audio);
				// this.audio.play();
				this.audio.src = this.voiceBlob[this.audioName];
				this.audio.load()
				if(this.onPlay){
					this.audio.pause()
					this.audio.currentTime = 0;
					this.onPlay = false
					this.audioPlay()
					return
				}
				this.audio.play().then(()=>{
					this.onPlay = true
				}).catch(()=>{
					console.log("error");
					// this.audioPlay()
					this.audio.play()
				});
			},
			countPlus(x, y) {
				// this.audio.volume = 1;
				this.countPlusFlag = true;
				this.initAudio()
				let duration = this.duration;
				//#ifdef APP-PLUS
				plus.device.vibrate(50);
				//#endif
				//#ifdef H5
				if (globalData.device != "ios") {
					uni.vibrateShort()
				}
				//#endif
				//#ifdef MP-WEIXIN
				uni.vibrateShort()
				//#endif
				let num = 0
				
				if(this.addType == "plus"){
					num = BigInt(this.count)  + BigInt(this.plusCount);
				}else{
					num = BigInt(this.count)  - BigInt(this.plusCount);
				}
				const arItem = {
					id: num.toString(),
					render: true,
					x: x,
					y: y,
					opacity: 1,
					voice: false //是否敲
				}
				this.plusArr.push(arItem);
				this.count = num.toString();
				uni.setStorage({
					key: "count",
					data: this.count + ''
				})
				this.$refs.CanvasDom.renderText(this.plusArr)
			},
			countPlusEnd() {
				this.countPlusFlag = false;
				this.$refs.CanvasDom.drawImage()
			},
			toZero() {
				this.count = this.defaultCount;
				uni.setStorage({
					key: "count",
					data: this.count
				})
			},
			toSetting() {
				uni.navigateTo({
					url: "/pages/setting/setting"
				})
			},
		},
		mounted() {
			this.count = uni.getStorageSync("count") ? uni.getStorageSync("count") : 0;
			uni.createSelectorQuery().in(this).select(".content").fields({
				node: true,
				size: true
			}, (res) => {
				this.canvasInfo["width"] = res.width;
				this.canvasInfo["height"] = res.height;
				this.renderCanvasDom = true;
			}).exec()
		},
		onShareAppMessage(obj) {
			return this.getAppData.shareObj
		},
	}
</script>

<style lang="scss" scoped>
	.content {
		color: #fff;
		height: 100vh;
		overflow: hidden;
		position: relative;

		.mask-confirm {
			height: 100%;
			position: absolute;
			width: 100%;
			top: 0;
			left: 0;
			z-index: 10;
			background-color: rgba(0, 0, 0, 0.8);
			display: flex;
			align-items: center;
			justify-content: center;

			.btn {
				width: 60%;
				height: 75rpx;
				line-height: 75rpx;
				background-color: #fff;
				color: #333;
				font-size: 45rpx;
				text-align: center;
				border-radius: 100rpx;
			}
		}

		.center {
			text-align: center;
			line-height: 45rpx;
		}

		.iconBox {
			position: fixed;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			width: 450rpx;
			height: 450rpx;
			border: 1rpx solid #fff;

			.plusTextChilds {
				position: absolute;
				top: 20rpx;
				right: 0;
				z-index: 1;

				text {
					font-size: 38rpx;
				}
			}

			.icon {
				width: 100%;
				display: block;
				position: relative;
				z-index: 2;
				touch-callout: none;
				-webkit-touch-callout: none;
				-ms-touch-callout: none;
				-moz-touch-callout: none;
			}
		}

		.scale_2 {
			transform: scale(0.9);
		}

		.topSetting {
			// #ifndef MP-WEIXIN
			padding: 15rpx 20rpx;
			// #endif
			// #ifdef MP-WEIXIN
			padding: 0rpx 20rpx;
			// #endif
			display: flex;
			// align-items: center;
			justify-content: space-around;

			.left {
				width: 50%;
				display: flex;
				align-items: center;
				flex-wrap: wrap;
				.gongDeCount{
					white-space: pre-wrap;
					word-wrap: break-word;
					border: 1rpx solid #fff;
				}
				text {
					display: inline-block;
					color: #fff;
					line-height: 100%;
					font-size: 32rpx;

					&:first-child {
						width: 100rpx;
					}

					&:last-child {
						width: calc(100% - 100rpx);
						word-break: break-all;
					}
				}
			}

			.right {
				width: 50%;
				display: flex;
				justify-content: flex-end;
				align-items: flex-start;

				.setting {
					display: inline-block;
					border: 2rpx solid #fff;
					// justify-self: end;
					border-radius: 8rpx;
					padding: 10rpx 15rpx;
				}

				.zeroBtn {
					display: inline-block;
					background-color: #eee;
					color: #333;
					border-radius: 8rpx;
					padding: 10rpx 15rpx;
					margin-right: 30rpx;
					opacity: 1;

					&:active {
						opacity: 0.8;
					}
				}
			}

		}
	}
</style>
